//
//  UIImageHelper.swift
//  CommonTools
//
//  Created by xianquan on 2023/11/30.
//

import Foundation
import TYUIKit

extension UIImage {
    public enum NameInBundle {
        case commonTools(String)
        case homeModule(String)
        case mineModule(String)
        case loginModule(String)
        case pointReadingModule(String)
        case dictionaryModule(String)
        case dictationModule(String)
        case rememberWordModule(String)
        case newWordModule(String)
        case videoModule(String)
        case vipCenterModule(String)
        case practiceModule(String)
        case syncTutorModule(String)
        
        var bundleName: String? {
            
            switch self {
//            case .homeModule:
//                return "HomeModule"
            default:
                return nil
            }
        }
        
        var podName: String? {
            
            switch self {
//            case .homeModule:
//                return "HomeModule"
            default:
                return nil
            }
        }
    }
    
    /// 获取图片，默认定义的枚举需要与模块名和bundle名相同，如不同，需要在NameInBundle中自定义
    public convenience init?(nameInBundle: NameInBundle){
        
        var name = "\(nameInBundle)"
        name = name.replacingOccurrences(of: "(\"", with: ".")
        name = name.replacingOccurrences(of: "\")", with: "")
        let upName = name.upperFirstLetter
        let arr = upName.components(separatedBy: ".")
        let bundleName = nameInBundle.bundleName ?? arr.first
        let podName = nameInBundle.podName ?? bundleName
        let imageName = arr.last ?? ""
        let bundle = Bundle(bundleName: bundleName ?? "", podName: podName ?? "")
        self.init(named: imageName, in: bundle, compatibleWith: nil)
    }
    
    public static func imageIn(bundleName: NameInBundle, originSize: CGSize?) -> UIImage?{
        var image = UIImage(nameInBundle: bundleName)
        if let originSize = originSize {
            image = image?.byResize(to: TY_ScreenAdaptionSize(originSize))
        }
        return image
    }
    
    /// 供OC使用,名称传入类似 "HomeModule/yourimageName"
    @objc public static func image(bundleName name: String) -> UIImage?{
        var arr = (name as NSString).components(separatedBy: "/")
        if arr.count < 2 {
            return nil
        }
        let bundleName = arr.removeFirst()
        let imageName = (arr as NSArray).componentsJoined(by: "/")
        return image(named: imageName, bundleName: bundleName, podName: nil)
    }
    /// 供OC使用,不传podName则默认与bundleName相同
    @objc public static func image(named name: String, bundleName: String) -> UIImage?{
        return image(named: name, bundleName: bundleName, podName: nil)
    }
    /// 供OC使用
    @objc public static func image(named name: String, bundleName: String, podName: String?) -> UIImage?{
        let bundle = Bundle(bundleName: bundleName , podName: podName ?? bundleName)
        return UIImage.init(named: name, in: bundle, compatibleWith: nil)
    }
}

/// 带圈数字
extension UIImage {
    @objc public static func circleAroundDigit(_ num:Int, circleColor: UIColor = .white,
                                               digitColor: UIColor, strokeColor: UIColor, diameter: CGFloat, space: CGFloat, cornerRadius: CGFloat = 0,
                           font: UIFont) -> UIImage {
    //    precondition((0...200).contains(num), "digit is not a digit")
        let p = NSMutableParagraphStyle()
        p.alignment = .center
        let s = NSAttributedString(string: String(num), attributes: [.font:font, .foregroundColor: digitColor, .paragraphStyle: p])
        let boderWidth = adapt(1)
        
        let r = UIGraphicsImageRenderer(bounds: CGRect(x: -space, y: 0, width: diameter + 2 * space, height: diameter ))
        return r.image {con in
            circleColor.setFill()
            let width = diameter - 2 * boderWidth
            let rect = CGRect(x: boderWidth, y: boderWidth , width: width, height: width)
            
            if cornerRadius == 0 {
                con.cgContext.fillEllipse(in: rect)
                
                strokeColor.setStroke()
                let path = UIBezierPath(ovalIn: rect)
                path.lineWidth = boderWidth
                path.stroke()
            }
            else {
//                con.cgContext.fill(rect)
                strokeColor.setStroke()
                let path = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius)
                path.lineWidth = boderWidth
                path.stroke()
                path.fill()
            }
            
            s.draw(in: CGRect(x: boderWidth, y: diameter / 2 - font.lineHeight / 2 -  boderWidth,
                              width: width, height: width))
            
        }
    }
}

public extension UIImage {
    
    enum CropXType {
        /// 横向不裁剪
        case full
        /// 横向全部裁剪
        case content
        /// 左边裁剪，右边不裁剪
        case left(leftMargin: CGFloat, contentWidth: CGFloat)
        case center(leftSpace: CGFloat, contentWidth: CGFloat)
    }
    
    func cropWhiteImage(cropXType: CropXType) -> UIImage? {
//        let image = resizewithQuality(.none, rate: screenScale)
        guard let cgImage = cgImage else { return nil }
        let width = size.width
        let height = size.height
        let bounds = CGRect(x: 0, y: 0, width: width, height: height)
 
        // 1. 创建图片上下文
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
        guard let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) else { return nil }
 
        // 2. 绘制图片
        context.draw(cgImage, in: bounds)
 
        // 3. 扫描图片颜色信息，寻找非白色区域
        guard let imageData = context.data else { return nil }
        let pixelData = imageData.bindMemory(to: UInt8.self, capacity: Int(width * height * 4))
        
        // 初始化边界值
        var minX = CGFloat(width)
        var maxX: CGFloat = 0
        var minY = CGFloat(height)
        var maxY = 0.0//CGFloat = 0
 
        // 扫描图片像素
        let intHeight = Int(height)
        let intWidth = Int(width)
        for y in 5..<intHeight {
            for x in 5..<intWidth {
                let pixelIndex = (y * intWidth + x) * 4
                let r = pixelData[pixelIndex]
                let g = pixelData[pixelIndex + 1]
                let b = pixelData[pixelIndex + 2]
                let a = pixelData[pixelIndex + 3]
                if r == 0 || g == 0 || b == 0 {
                    continue
                }
                let floatX = CGFloat(x)
                let floatY = CGFloat(y)
 
                if 255 - r > 2 || 255 - g > 2 || 255 - b > 2 || a != 255 {
                    // 发现非白色像素
                    if floatX < minX {
                        minX = floatX
                    }
                    if floatX > maxX {
                        maxX = floatX
                    }
                    if floatY < minY  {
                        minY = floatY
                    }
                    if floatY > maxY {
                        maxY = floatY
                    }
                }
            }
        }
 
        // 4. 裁剪图片
        if minX < maxX && minY < maxY {
            var cropRect: CGRect = CGRect(x: 0, y: (minY - 5) * screenScale , width: width * screenScale, height: (maxY - minY + 10) * screenScale )
            switch cropXType {
            case .full:
                break
//                cropRect = CGRect(x: 0, y: (minY - 5) * screenScale , width: width * screenScale, height: (maxY - minY + 10) * screenScale )
            case .content:
                cropRect = CGRect(x: minX * screenScale, y: cropRect.minY, width: (maxX - minX) * screenScale, height: cropRect.height)
            case let .left(leftMargin, contentWidth):
                cropRect = CGRect(x: (minX - leftMargin) * screenScale, y: cropRect.minY, width: (max(contentWidth, maxX) + 2 * minX) * screenScale, height: cropRect.height)
            case let .center(leftSpace, contentWidth):
                cropRect = CGRect(x: (minX - leftSpace) * screenScale, y: cropRect.minY, width: (contentWidth + 2 * leftSpace) * screenScale, height: cropRect.height)
            }
            if let cgImage = cgImage.cropping(to: cropRect) {
                return UIImage(cgImage: cgImage)
            }
        }
 
        return nil
    }
    
    func isEmptyImage() -> Bool {
        return self.size.width == 0 || self.size.height == 0
    }
}
